package io.bdmc.common.http;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.bdmc.common.utils.RedisUtils;
import io.bdmc.modules.bss.model.alarm.GatewayZxy;

@Service
public class ZxyHttpUtil {
    public static final Logger logger = LoggerFactory.getLogger((ZxyHttpUtil.class));

    private static String apiBaseUrl = "https://www.zxyun119.com/thirdPartyApi/ThreePlaceREST";// 地址
    private static String loginBasrUrl = "https://www.zxyun119.com/thirdPartyApi/login";

    private static String appKey = "cAGANpUMr1mVykF7IFXQdOx4";
    private static String masterSecret = "iZJP904V58qY4I3up8nzdicpLiZ5mw";
    private static String getTokenAPi = "/api/1.0/auth/getToken";// 获取token
    private static String checkTokenApi = "/api/1.0/auth/checkToken";// checktoken
    private static String insertGatewayApi = "/api/1.0/project/insertGateway";// 批量添加网关（设备）
    private static String deleteGatewayApi = "/api/1.0/deviceUnBind";// 删除网关
    private static String setPushPathApi = "/api/1.0/setPushPath";// 设置推送网关
    private static String  deviceAttributeUrl="/api/1.0/getDeviceAttribute";//获取设备属性
    private static String deviceList="/api/1.0/project/device/gateway/getDeviceList";//获取网关下设备信息

    @Autowired
    private HttpClientUtil _httpSvs;

    @Autowired
    public RedisUtils _redis;

    /** 获取中消云accesstoken */
    private String getZxyApiAccessToken() {
        try {
            String existToken = _redis.get("ZXY_API_TOKEN");
            if (existToken != null) {
                boolean isValidToken = checkZxyApiToken(existToken);
                if (isValidToken)
                    return existToken;
            }
            HashMap<String, String> map = new LinkedHashMap<>();
            map.put("appkey", appKey);
            map.put("masterSecret", masterSecret);
            String jsonParam = JSONObject.toJSONString(map);
            HttpResult re = _httpSvs.doPostJson(loginBasrUrl + getTokenAPi, jsonParam);
            if (re.getCode() == 200) {
                String body = re.getBody();
                ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
                if (resp.getCode().equals("000000")) {
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(resp.getData()));
                    String token = jsonObject.get("apiToken").toString();
                    _redis.set("ZXY_API_TOKEN", token);
                    return token;
                }
            }
            return "";
        } catch (Exception e) {
            logger.error("getAccessToken:" + e.getMessage());
            return "";
        }
    }

    /**
     * 验证token有效性
     * 
     * @param accessToken
     * @return
     */
    public boolean checkZxyApiToken(String accessToken) {
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", accessToken);
        HttpResult re;
        try {
            re = _httpSvs.doPostJson(loginBasrUrl + checkTokenApi, null, map);
            if (re.getCode() == 200) {
                String body = re.getBody();
                ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
                if (resp.getCode().equals("000000")) {// token有效
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            logger.error("checkZxyApiToken:" + e.getMessage());
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 批量添加网关（设备）
     * 
     * @param gates
     * @return
     */
    public boolean insertGateway(List<GatewayZxy> gates) {
        String token = getZxyApiAccessToken();
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", token);
        JSONObject json = new JSONObject();
        json.put("gateWayList", gates);
        HttpResult re;
        try {
            re = _httpSvs.doPostJson(apiBaseUrl + insertGatewayApi, json.toJSONString(), map);
            if (re.getCode() == 200) {
                String body = re.getBody();
                ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
                if (resp.getCode().equals("000000")) {// 成功返回00000
                    return true;
                } else {
                    logger.error("insertGateway:" + body);
                }
            }
            return false;
        } catch (Exception e) {
            logger.error("insertGateway:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除单个网关
     * 
     * @param gatewayName
     * @return 成功与否
     */
    public boolean deleteGateway(String gatewayName) {
        String token = getZxyApiAccessToken();
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", token);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("gatewayName", gatewayName);
        String param = jsonObject1.toJSONString();
        HttpResult re;
        try {
            re = _httpSvs.doPostJson(apiBaseUrl + deleteGatewayApi, param, map);
            if (re.getCode() == 200) {
                String body = re.getBody();
                ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
                if (resp.getCode().equals("000000")) {// 成功返回00000
                    return true;
                } else {
                    logger.error("deleteGateway:" + body);
                }
            }
            return false;
        } catch (Exception e) {
            logger.error("deleteGateway:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

        /**
     * 设置推送地址
     * 
     * @param pushPath 推送地址
     * @return 成功与否
     */
    public boolean setPushPath(String pushPath) {
        String token = getZxyApiAccessToken();
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", token);
        HttpResult re;
        try {
            re = _httpSvs.doGet(apiBaseUrl+setPushPathApi+"?pushPath="+pushPath,  map);
            if (re.getCode() == 200) {
                String body = re.getBody();
                ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
                if (resp.getCode().equals("000000")) {// 成功返回00000
                    return true;
                } else {
                    logger.error("setPushPath:" + body);
                }
            }
            return false;
        } catch (Exception e) {
            logger.error("setPushPath:" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取设备属性
     *
     */
    public  String getDeviceAttribute(String deviceId){
        String token = getZxyApiAccessToken();
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", token);
        HttpResult re;
        String str="";
        try {
            re = _httpSvs.doGet(apiBaseUrl+deviceAttributeUrl+"?deviceId="+deviceId,  map);
            if (re.getCode() != 200) {
                logger.error("getDeviceAttribute:"+re.getBody());
                return str;
            }
            String body = re.getBody();
            ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
            if (resp.getCode().equals("000000")) {// 成功返回00000
                str = resp.getData().toString();
            } else {
                logger.error("getDeviceAttribute:" + body);
            }
            return str;
        } catch (Exception e) {
            logger.error("getDeviceAttribute:" + e.getMessage());
            e.printStackTrace();
            return str;
        }
    }

    /**
     * 获取网关下设备列表
     *
     */
    public  String getDeviceList(String imei){
        String token = getZxyApiAccessToken();
        HashMap<String, String> map = new LinkedHashMap<>();
        map.put("API_TOKEN", token);
        HttpResult re;
        String str="";
        try {
            re = _httpSvs.doGet(apiBaseUrl+deviceList+"?gatewayName="+imei,  map);
            if (re.getCode() != 200) {
                logger.error("getDeviceAttribute:"+re.getBody());
                return str;
            }
            String body = re.getBody();
            ZxyResponse resp = JSONObject.parseObject(body, ZxyResponse.class);
            if (resp.getCode().equals("000000")) {// 成功返回00000
                str = resp.getData().toString();
            } else {
                logger.error("getDeviceList:" + body);
            }
            return str;
        } catch (Exception e) {
            logger.error("getDeviceList:" + e.getMessage());
            e.printStackTrace();
            return str;
        }
    }
}